const db = require("../utils/db");
const util = require("../utils/util.js");

// 添加一级评论
exports.addComment = async (ctx) => {
  let { article_id, user_id, contents } = ctx.request.body;
  let other=[ ];
  // 验证用户是否已经在数据库中
  let res = await new Promise((resolve, reject) => {
    let sqlLang = `select * from user where id='${user_id}'`;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (!res) {
    util.responseClient(ctx, 200, 1, "用户不存在");
    return;
  }

  let userInfo = {
    user_id: res[0].id,
    avatar: res[0].avatar,
    name: res[0].name,
  };

  let newComment = await new Promise((resolve, reject) => {
    // 生成token name, password, phone, email, introduce, type
    // const token = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, 'secret', { expiresIn: 3600 })
    return db.query(
      `insert into comment (article_id,content,user_id,user,other_comments) values ('${article_id}', '${contents}', '${user_id}', '${JSON.stringify(
        userInfo
      )}',JSON_Array())`,
      (error, data) => {
        if (error) throw error;
        // 已插入数据，
      resolve(data)
      }
    );
  });

  if (newComment) {
    //更新观看人数
    let article = await new Promise((resolve, reject) => {
      let sqlLang = `select * from article where id='${article_id}' `;
      return db.query(sqlLang, (err, data) => {
        if (err) throw err;
        if (data.length > 0) {
          resolve(data);
        } else {
          resolve(false);
        }
      });
    });
    if(!article){
        util.responseClient(ctx, 200, 1, "该文章不存在！");
        return;
       }
   
    if (article) {
      //观看人数+1
      let cnt = 1 + parseInt(JSON.parse(article[0].meta).views);
      let time=util.timestampToTime(new Date())
      await new Promise((resolve, reject) => {
        // let sqlLang = `update article set meta='${res[0].meta}' where id='${id}' `;JSON.stringify(me
        let sqlLang = `update article set meta = JSON_REPLACE(meta, '$.views', '${cnt}') , comments =JSON_ARRAY_APPEND(comments,"$",
        JSON_OBJECT("id",'${newComment.insertId}',"user",JSON_OBJECT("user_id",'${res[0].id}',"name",'${ res[0].name}',"avatar",'${res[0].avatar}'),"create_time",'${time}',"content",'${contents}')
        ) where id='${article_id}' `;
        return db.query(sqlLang, (err, data) => {
          if (err) throw err;
          resolve(data);
        });
      });
     
    }
     util.responseClient(ctx, 200, 0, "操作成功 ！");
  }
};
exports.addThirdCom = async (ctx) => {
  let { article_id, comment_id, user_id, contents, to_user } = ctx.request.body;
  let to_id=to_user.user_id,to_name=to_user.name,to_avatar=to_user.avatar
  let comment = await new Promise((resolve, reject) => {
    let sqlLang = `select * from comment where id='${comment_id}'`;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (!comment) {
    util.responseClient(ctx, 200, 1, "改评论不存在！");
    return;
  }

  let user = await new Promise((resolve, reject) => {
    let sqlLang = `select * from user where id='${user_id}'`;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (!user) {
    util.responseClient(ctx, 200, 1, "改用户不存在！");
    return;
  }
     let userInfo = {
    user_id: user[0].id,
    name: user[0].name,
    avatar: user[0].avatar,
    };
    let time=util.timestampToTime(new Date())
  let thirdcom=await new Promise((resolve, reject) => {
    // let sqlLang = `update article set meta='${res[0].meta}' where id='${id}' `;JSON.stringify(me
    let sqlLang = `update comment set other_comments =JSON_ARRAY_APPEND(other_comments,"$",JSON_OBJECT("user",JSON_OBJECT("user_id",'${user[0].id}',"name",'${ user[0].name}',"avatar",'${user[0].avatar}'),"content",'${contents}',"to_user",JSON_OBJECT("user_id",'${parseInt(to_id)}',"name",'${to_name}',"avatar",'${to_avatar}'),"create_time",'${time}') )where id='${comment_id}' `;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
       resolve(data)
    });
  });
  if (thirdcom) {
    //更新观看人数
    let article = await new Promise((resolve, reject) => {
      let sqlLang = `select * from article where id='${article_id}' `;
      return db.query(sqlLang, (err, data) => {
        if (err) throw err;
        if (data.length > 0) {
          resolve(data);
        } else {
          resolve(false);
        }
      });
    });
    if(!article){
     util.responseClient(ctx, 200, 1, "改文章不存在！");
     return;
    }
    if (article) {
      //观看人数+1
      let cnt = 1 + parseInt(JSON.parse(article[0].meta).comments);
      await new Promise((resolve, reject) => {
        // let sqlLang = `update article set meta='${res[0].meta}' where id='${id}' `;JSON.stringify(me
        let sqlLang = `update article set meta = JSON_REPLACE(meta, '$.comments', '${cnt}')  where id='${article_id}' `;
        return db.query(sqlLang, (err, data) => {
          if (err) throw err;
          console.log(data);
          resolve(data);
        });
      }); 
      
    }
   util.responseClient(ctx, 200, 0, "操作成功 ！");
  } /***/
  // let { article_id, comment_id, user_id, content, to_user } = req.body;
  // Comment.findById({
  //   _id: comment_id,
  // })
  //   .then(commentResult => {
  //     User.findById({
  //       _id: user_id,
  //     })
  //       .then(userResult => {
  //         if (userResult) {
  //           let userInfo = {
  //             user_id: userResult._id,
  //             name: userResult.name,
  //             type: userResult.type,
  //             avatar: userResult.avatar,
  //           };
  //           let item = {
  //             user: userInfo,
  //             content: content,
  //             to_user: JSON.parse(to_user),
  //           };
  //           commentResult.other_comments.push(item);
  //           Comment.updateOne(
  //             { _id: comment_id },
  //             {
  //               other_comments: commentResult.other_comments,
  //               is_handle: 2,
  //             },
  //           )
  //             .then(result => {
  //               // responseClient(res, 200, 0, '操作成功', result);
  //               Article.findOne({ _id: article_id }, (errors, data) => {
  //                 if (errors) {
  //                   console.error('Error:' + errors);
  //                   // throw errors;
  //                 } else {
  //                   data.meta.comments = data.meta.comments + 1;
  //                   Article.updateOne({ _id: article_id }, { meta: data.meta })
  //                     .then(Articleresult => {
  //                       // console.log('result --------------:', Articleresult);
  //                       responseClient(
  //                         res,
  //                         200,
  //                         0,
  //                         '操作成功 ！',
  //                         Articleresult,
  //                       );
  //                     })
  //                     .catch(err => {
  //                       // console.log('err ===========:', err);
  //                       throw err;
  //                     });
  //                 }
  //               });
  //             })
  //             .catch(err1 => {
  //               console.error('err1:', err1);
  //               responseClient(res);
  //             });
  //         } else {
  //           responseClient(res, 200, 1, '用户不存在');
  //         }
  //       })
  //       .catch(error => {
  //         console.error('error :', error);
  //         responseClient(res);
  //       });
  //   })
  //   .catch(error2 => {
  //     console.error('error2 :', error2);
  //     responseClient(res);
  //   });
};

exports.getOtherCom=async(ctx)=>{
  //  console.log(ctx)
    let id= ctx.query.comId;
    // console.log(ctx.query)
   let responseData = {
    list: [],
   };
     let res=await new Promise((resolve, reject)=>{
        let sqlLang = `select other_comments from comment where id='${id}'`;
        return db.query(sqlLang, (err, data)=>{
          if (err) throw err;
          else { 
            // console.log(data)
            // console.log(data[0])
            // data[0].forEach(item=>{
            //   console.log("item:",item);
            // })
            responseData.list=JSON.parse(data[0].other_comments)
            console.log( responseData.list)
            responseData.list.forEach(item=>{
              console.log("item:",item);
            })
            // console.log(data[0].other_comments)
            // responseData.list = data;
            util.responseClient(ctx, 200, 0, 'success', responseData);
            resolve(data)  
          }
        })    
      })

}